package com.liuzhilin.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.liuzhilin.service.UserService;
import com.liuzhilin.util.Response;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
// 用户对文章的反馈，点赞，收藏，评论
@WebServlet("/userFeedback")
public class UserFeedback extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 设置CORS响应头
        Response.setCorsHeaders(response);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        PrintWriter out = response.getWriter();
        // 从请求体中获取JSON数据
        try {
            // 从请求体中获取JSON数据
            StringBuilder sb = new StringBuilder();
            BufferedReader reader = request.getReader();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            String json = sb.toString();
            // 解析JSON数据
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, Object> data = objectMapper.readValue(json, Map.class);
            String writer = (String) data.get("writer");
            String title = (String) data.get("title");
            String currentUsername = (String) data.get("currentUsername");
            Integer status = (Integer) data.get("status");
            String comment = (String) data.get("comment");
            // 对数据的具体处理交由专门的方法
            String result = UserService.feedback(writer, title, currentUsername, status, comment);
            out.print("{\"success\": true, \"message\": \"" + result + "\"}");
            response.setStatus(HttpServletResponse.SC_OK);
        } catch (Exception e) {
            e.printStackTrace();
            out.print("{\"success\": false, \"message\": \"服务器内部错误\"}");
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
    @Override
    public void doOptions(HttpServletRequest request, HttpServletResponse response) {
        // 设置CORS响应头
        Response.setCorsHeaders(response);
        response.setStatus(HttpServletResponse.SC_OK);
    }

}
